package com.liang.circle.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.circle.api.req.ShareCommentGetReq;
import com.liang.circle.api.req.ShareCommentReplySaveReq;
import com.liang.circle.api.vo.ShareCommentReplyVO;
import com.liang.circle.server.entity.po.ShareCommentReply;
import com.liang.circle.server.entity.po.ShareMoment;
import com.liang.circle.server.rpc.UserInfo;
import com.liang.circle.server.rpc.UserRpc;
import com.liang.circle.server.service.ShareCommentReplyService;
import com.liang.circle.server.mapper.ShareCommentReplyMapper;
import com.liang.circle.server.service.ShareMomentService;
import com.liang.circle.server.util.LoginUtil;
import com.liang.circle.server.util.TreeUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ShareCommentReplyServiceImpl extends ServiceImpl<ShareCommentReplyMapper, ShareCommentReply> implements ShareCommentReplyService {

    private final ShareCommentReplyMapper shareCommentReplyMapper;

    @Lazy
    private final ShareMomentService shareMomentService;
    private final UserRpc userRpc;

    @Override
    @Transactional
    public void saveComment(ShareCommentReplySaveReq requestParam) {
        ShareMoment shareMoment = shareMomentService.getById(requestParam.getMomentId());
        ShareCommentReply commentReply = BeanUtil.copyProperties(requestParam, ShareCommentReply.class);
        String loginId = LoginUtil.getLoginId();
        // 如果是评论
        if (requestParam.getReplyType() == 1) {
            commentReply.setParentId(-1L);
            commentReply.setToId(requestParam.getTargetId());
            commentReply.setToUser(loginId);
            commentReply.setToUserAuthor(shareMoment.getCreatedBy().equals(loginId) ? 1 : 0);
        } else {
            // 如果是回复
            commentReply.setParentId(requestParam.getTargetId());
            commentReply.setReplyId(requestParam.getTargetId());
            commentReply.setReplyUser(loginId);
            commentReply.setReplayAuthor(shareMoment.getCreatedBy().equals(loginId) ? 1 : 0);
        }
        if (CollUtil.isNotEmpty(requestParam.getPicUrlList())) {
            commentReply.setPicUrls(JSON.toJSONString(requestParam.getPicUrlList()));
        }
        // 回复数+1
        shareMomentService.updateMoment(shareMoment, 1);
        save(commentReply);
    }

    @Override
    public List<ShareCommentReplyVO> listComment(ShareCommentGetReq requestParam) {
        List<ShareCommentReply> list = lambdaQuery()
                .eq(ShareCommentReply::getMomentId, requestParam.getId())
                .select(ShareCommentReply::getId, ShareCommentReply::getMomentId, ShareCommentReply::getReplyType,
                        ShareCommentReply::getToUser, ShareCommentReply::getContent,
                        ShareCommentReply::getPicUrls, ShareCommentReply::getCreatedBy,
                        ShareCommentReply::getCreatedTime, ShareCommentReply::getUpdateBy)
                .list();
        List<String> usernameList = list.stream()
                .map(ShareCommentReply::getCreatedBy)
                .distinct()
                .collect(Collectors.toList());
        Map<String, UserInfo> userInfoMap = userRpc.batchGetUserInfo(usernameList);
        List<ShareCommentReplyVO> voList = list.stream().map(item -> {
            ShareCommentReplyVO vo = BeanUtil.copyProperties(item, ShareCommentReplyVO.class);
            vo.setPicUrlList(JSON.parseArray(item.getPicUrls(), String.class));
            if (item.getReplyType() == 2) {
                vo.setFromId(item.getCreatedBy());
                vo.setToId(item.getToUser());
            }
            UserInfo userInfo = userInfoMap.getOrDefault(item.getCreatedBy(), new UserInfo());
            vo.setUserName(userInfo.getNickname());
            vo.setAvatar(userInfo.getAvatar());
            return vo;
        }).collect(Collectors.toList());
        return TreeUtils.buildTree(voList);
    }

    @Override
    public void updateComment(Long id) {
        lambdaUpdate()
                .eq(ShareCommentReply::getMomentId, id)
                .set(ShareCommentReply::getIsDeleted, 1)
                .update();
    }

    @Override
    public void removeComment(Long id) {
//        ShareCommentReply commentReply = getById(id);
        ShareCommentReply commentReply = shareCommentReplyMapper.getById(id);
        List<ShareCommentReply> list = lambdaQuery()
                .eq(ShareCommentReply::getMomentId, commentReply.getMomentId())
                .select(ShareCommentReply::getId, ShareCommentReply::getMomentId,
                        ShareCommentReply::getReplyType, ShareCommentReply::getContent,
                        ShareCommentReply::getPicUrls, ShareCommentReply::getCreatedBy,
                        ShareCommentReply::getToUser, ShareCommentReply::getParentId)
                .list();
        List<ShareCommentReply> tree = TreeUtils.buildTree(list);
        List<ShareCommentReply> replyList = new ArrayList<>();
        // 获取所有回复添加到回复列表中
        for (ShareCommentReply reply : tree) {
            TreeUtils.findAll(replyList, reply, id);
        }
        // 关联子级对象及 moment 的回复数量
        Set<Long> ids = replyList.stream().map(ShareCommentReply::getId).collect(Collectors.toSet());
        lambdaUpdate()
                .eq(ShareCommentReply::getMomentId, commentReply.getMomentId())
                .in(ShareCommentReply::getId, ids)
                .remove();
        // 回复数
        ShareMoment shareMoment = ShareMoment.builder().id(Long.valueOf(commentReply.getMomentId())).build();
        shareMomentService.updateMoment(shareMoment, -replyList.size());
    }
}




